package com.wjm.myhookpluginloadedapk;

import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Environment;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class App extends Application {

    private Resources newResources;
    private AssetManager newAssetManager;
    public static String apkName = "/plugin-debug.apk";
    public static boolean isPlugin=false;
    private static Context  instance;
    public static Context getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        HookUtil hookUtil = new HookUtil();
        hookUtil.hookStartActivity(this);
        hookUtil.hookHookMh(this);
//        hookUtil.injectPluginClass();
//        String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/plugin.apk";
        String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + apkName;
        hookUtil.putLoadedApk(apkPath);

        //实现完插件中类的融合再实现插件的资源管理
//        String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + apkName;
//        String apkPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/plugin.apk";
        try {
            newAssetManager = AssetManager.class.newInstance();
            Method addAssetPath = newAssetManager.getClass().getDeclaredMethod("addAssetPath", String.class);
            addAssetPath.setAccessible(true);
            addAssetPath.invoke(newAssetManager, apkPath);
            Method ensureStringBlocks = AssetManager.class.getDeclaredMethod("ensureStringBlocks");
            ensureStringBlocks.setAccessible(true);
            ensureStringBlocks.invoke(newAssetManager);
            Resources resources = getResources();
            newResources = new Resources(newAssetManager, resources.getDisplayMetrics(), resources.getConfiguration());

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

//    @Override
//    public AssetManager getAssets() {
//        return super.getAssets();
//    }

    public AssetManager getAssetManager() {
        return newAssetManager == null ? super.getAssets() : newAssetManager;
    }

    @Override
    public Resources getResources() {
        return newResources == null ? super.getResources() : newResources;
//        return super.getResources();
    }
}
